using System.Collections;
using System.Collections.Generic;
using Main.NPC;
using Main.Transition;
using Main.UI;
using UnityEngine;
using UnityEngine.Tilemaps;

namespace Main.AStar
{
    public class AStarTest : MonoBehaviour
    {
        public AStarController aStarController;
        public Vector2Int startPos;
        public Vector2Int targetPos;
        public Tilemap displayMap;

        public TileBase displayTile;

        public bool displayStartAndTarget;

        public bool displayPath;

        public Stack<MovementStep> npcMovementStack;

        [SceneName] public string targetScene;
        public NPCMovement npc;
        public bool moveNpc;
        public AnimationClip animationClip;

        private void Start()
        {
            npcMovementStack = new Stack<MovementStep>();
        }

        private void Update()
        {
            ShowPathOnGridMap();

            if (Input.GetMouseButtonDown(0) && moveNpc)
            {
                var ScheduleDetails = new ScheduleDetails(0, 0, 0, 0, Season.Spring, targetScene, (Vector2Int)CursorManager.MouseGridPos, animationClip, true);
                npc.BuildPath(ScheduleDetails);
            }
        }

        private void ShowPathOnGridMap()
        {
            if (displayMap != null && displayTile != null)
            {
                if (displayStartAndTarget)
                {
                    displayMap.SetTile((Vector3Int)startPos, displayTile);
                    displayMap.SetTile((Vector3Int)targetPos, displayTile);
                }
                else
                {
                    displayMap.SetTile((Vector3Int)startPos, null);
                    displayMap.SetTile((Vector3Int)targetPos, null);
                }

                if (displayPath)
                {
                    var sceneName = SceneTransitionManager.CurrentScene;

                    aStarController.BuildPath(sceneName, startPos, targetPos, npcMovementStack);

                    foreach (var step in npcMovementStack)
                    {
                        displayMap.SetTile((Vector3Int)step.gridCoordinate, displayTile);
                    }
                }
                else
                {
                    if (npcMovementStack.Count > 0)
                    {
                        foreach (var step in npcMovementStack)
                        {
                            displayMap.SetTile((Vector3Int)step.gridCoordinate, null);
                        }
                        npcMovementStack.Clear();
                    }
                }
            }
        }
    }
}